package com.longtxt.core.ble.main

import android.bluetooth.BluetoothDevice
import com.jieli.bluetooth_connect.constant.BluetoothConstant
import com.jieli.jl_rcsp.constant.StateCode
import com.jieli.jl_rcsp.impl.RcspAuth
import com.jieli.jl_rcsp.impl.WatchOpImpl
import com.jieli.jl_rcsp.interfaces.watch.OnWatchOpCallback
import com.jieli.jl_rcsp.model.NotificationMsg
import com.jieli.jl_rcsp.model.WatchConfigure
import com.jieli.jl_rcsp.model.base.BaseError
import com.longtxt.core.ble.BleManager
import timber.log.Timber


class JLWatchManager : WatchOpImpl(FUNC_WATCH) {

    private var mBlePeripheral: BlePeripheral? = null
    private var isAuthPass = false

    private val mRCSPAuth = RcspAuth({ d, p1 -> sendDataToDevice(d, p1) },
        object : RcspAuth.OnRcspAuthListener {
            override fun onInitResult(p0: Boolean) {
                isAuthPass = false
            }

            override fun onAuthSuccess(p0: BluetoothDevice?) {
                Timber.tag("JLWatchManager").d("onAuthSuccess")
                isAuthPass = true
                notifyBtDeviceConnection(connectedDevice, StateCode.CONNECTION_OK)
                BleManager.bleStateToConnected()
            }

            override fun onAuthFailed(p0: BluetoothDevice?, p1: Int, p2: String?) {
                Timber.tag("JLWatchManager").d("onAuthFailed")
                BleManager.bleStateToDisconnected()
                isAuthPass = false
            }
        })

    override fun getConnectedDevice(): BluetoothDevice {
        return mBlePeripheral?.mDevice!!
    }

    override fun sendDataToDevice(p0: BluetoothDevice?, p1: ByteArray?): Boolean {
        if (p0 == null || p1 == null) {
            return false
        }
        return mBlePeripheral?.writeJLRequest(p1) == true
    }

    fun notifyReceivedData(data: ByteArray) {
        if (mBlePeripheral?.mDevice == null) {
            return
        }

        if (!isAuthPass) {
            mRCSPAuth.handleAuthData(connectedDevice, data)
        } else {
            notifyReceiveDeviceData(connectedDevice, data)
        }
    }

    fun changeAuthState(state: Boolean) {
        Timber.tag("JLWatchManager").d("changeAuthState:$state")
        isAuthPass = state
    }

    private fun convertWatchConnectStatus(status: Int): Int {
        val newStatus: Int = when (status) {
            BluetoothConstant.CONNECT_STATE_CONNECTING -> StateCode.CONNECTION_CONNECTING
            BluetoothConstant.CONNECT_STATE_CONNECTED -> StateCode.CONNECTION_OK
            else -> StateCode.CONNECTION_DISCONNECT
        }
        return newStatus
    }

    fun notifyConnectionState(device: BluetoothDevice, state: Int) {
        if (state != 2) {
            notifyBtDeviceConnection(device, convertWatchConnectStatus(state))
        }
    }

    fun setUpDevice(bleService: BlePeripheral) {
        mBlePeripheral = bleService
        mRCSPAuth.stopAuth(connectedDevice, false)
        mRCSPAuth.startAuth(connectedDevice)
    }

    fun sendNotifications(appName: String, title: String, content: String, flag: Int) {
        Timber.tag("JLWatchManager")
            .d("sendNotifications,appName:$appName,content:$content,flag:$flag")
        val msg = NotificationMsg()
            .setAppName(appName)
            .setContent(content)
            .setFlag(flag)
            .setTime(System.currentTimeMillis())
            .setOp(NotificationMsg.OP_PUSH)

        if (title.isNotEmpty()) {
            msg.title = title
        }
        pushMessageInfo(msg, object : OnWatchOpCallback<Boolean?> {
            override fun onSuccess(result: Boolean?) {
                Timber.tag("JLWatchManager").d("pushMessageInfo onSuccess")
            }

            override fun onFailed(error: BaseError) {
                //回调失败
                //error： 错误信息
                Timber.tag("JLWatchManager").d("pushMessageInfo onFailed $error")
            }
        })
    }


    fun readWatchConfig(): WatchConfigure = getWatchConfigure(connectedDevice)

    companion object {
        val shared = JLWatchManager()
    }
}